//
//  SBNaviSegment.m
//  Pods
//
//  Created by 刘 真 on 7/26/16.
//
//

#import "SBNaviSegment.h"
#import "SBPageController.h"

@interface SBNaviSegment ()
@property (nonatomic) BOOL touching;
@property (nonatomic, strong) NSMutableDictionary *dots;
@end

@implementation SBNaviSegment

- (instancetype)init {
    self = [super init];
    if (self) {
        _indicator = [[UIView alloc] init];
        _indicator.backgroundColor = [UIColor colorWithRed:0.1608 green:0.6824 blue:0.1922 alpha:1.0];
        [self addSubview:_indicator];
        self.backgroundColor = [UIColor clearColor];
        
        self.dots = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    
    CGFloat totalWidth = 0;
    UIFont *font = [UIFont  systemFontOfSize:16];
    NSDictionary *attributes = @{NSFontAttributeName : font, NSForegroundColorAttributeName : [UIColor colorWithRed:0.3989 green:0.3989 blue:0.3989 alpha:1.0]};
    NSDictionary *selectedAttributes = @{NSFontAttributeName : font, NSForegroundColorAttributeName : [UIColor colorWithRed:0.1608 green:0.6824 blue:0.1922 alpha:1.0]};
    
    CGRect contentRect = CGRectInset(rect, 5, 5);
    for (NSString *item in self.items) {
        CGRect textBounds = [item boundingRectWithSize:contentRect.size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
        totalWidth += CGRectGetWidth(textBounds);
    }
    
    CGFloat w = CGRectGetWidth(rect);
    CGFloat padding = (w - totalWidth)/(self.items.count + 1);
    
    //draw
    CGFloat y = (CGRectGetHeight(rect) - font.lineHeight)/2.0;
    CGPoint origin = CGPointMake(padding, y);
    
    for (NSString *item in self.items) {
        NSInteger idx = [self.items indexOfObject:item];
        BOOL selected = self.hideIndicator ? NO : idx == self.selectedIndex;
        [item drawAtPoint:origin withAttributes:selected ? selectedAttributes : attributes];
        CGRect textBounds = [item boundingRectWithSize:contentRect.size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
        origin.x += CGRectGetWidth(textBounds);
        
        //绘制小红点
        BOOL show = [self.dots[@(idx)] boolValue];
        if (show) {
            CGContextRef context = UIGraphicsGetCurrentContext();
            CGContextSaveGState(context);
            CGRect dotFrame = CGRectMake(origin.x + 2, origin.y - 2, 5, 5);
            CGContextSetFillColorWithColor(context, [UIColor colorWithRed:0.9051 green:0.2303 blue:0.2588 alpha:1.0].CGColor);
            CGContextFillEllipseInRect(context, dotFrame);
            CGContextRestoreGState(context);
        }
        
        origin.x += padding;
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self updateIndicator];
}

- (void)updateIndicator {
    NSInteger count = [self.items count];
    
    if (count > 0) {
        CGFloat width = CGRectGetWidth(self.bounds);
        CGFloat height = CGRectGetHeight(self.bounds);
        CGFloat iw = (width - self.indicatorLeftMargin - self.indicatorRightMargin + self.indicatorPadding) / count - self.indicatorPadding;
        CGRect frame = CGRectMake(self.indicatorLeftMargin + self.selectedIndex * (iw + self.indicatorPadding), height - 1, iw, 1);
        _indicator.frame = frame;
    }
    
    _indicator.hidden = _hideIndicator;
}

- (NSInteger)touchIndexWithPoint:(CGPoint)point {
    
    //如果不在控件内，则直接返回
    if (!CGRectContainsPoint(self.bounds, point)) {
        return NSNotFound;
    }
    
    //
    NSInteger count = [self.items count];
    CGFloat width = CGRectGetWidth(self.bounds);
    CGFloat itemWidth = width/count;
    NSInteger idx = floor(point.x / itemWidth);
    return idx;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    CGPoint point = [[touches anyObject] locationInView:self];
    
    //如果不在控件内，则直接返回
    if (CGRectContainsPoint(self.bounds, point)) {
        _touching = YES;
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    CGPoint point = [[touches anyObject] locationInView:self];
    
    //如果移出当前控件，则无效
    if (!CGRectContainsPoint(self.bounds, point)) {
        _touching = NO;
        return;
    }
    
    if (_touching) {
        NSInteger idx = [self touchIndexWithPoint:point];
        [self selectIndex:idx animated:YES];
    }
    _touching = NO;
}

- (void)selectIndex:(NSInteger)index animated:(BOOL)animated {
    if (index > self.selectedIndex) {
        [self.pageController moveNext];
    }
    else if (index < self.selectedIndex) {
        [self.pageController moveBefore];
    }
    self.selectedIndex = index;
    
    [UIView animateWithDuration:0.25 animations:^{
        [self updateIndicator];
    }];
}

- (void)moveIndicator:(CGFloat)postion {
    
    NSInteger count = [self.items count];
    
    if (count > 0) {
        CGFloat width = CGRectGetWidth(self.bounds);
        
        CGFloat iw = (width - self.indicatorLeftMargin - self.indicatorRightMargin + self.indicatorPadding) / count - self.indicatorPadding;
        
        CGFloat x = self.indicatorLeftMargin + self.selectedIndex * (iw + self.indicatorPadding) + iw/2.0f;
        CGFloat dx = (iw + self.indicatorPadding) * postion;
        CGPoint center = _indicator.center;
        center.x = x + dx;
        _indicator.center = center;
    }
}

- (void)setDotForIndex:(NSInteger)index {
    if (self.dots) {
        [self.dots setObject:@YES forKey:@(index)];
    }
    [self setNeedsDisplay];
}

- (void)cleanDotForIndex:(NSInteger)index {
    if (self.dots) {
        [self.dots removeObjectForKey:@(index)];
    }
    [self setNeedsDisplay];
}

@end
